/******************************************************************************
@file:  TradeHome.java
@author Ramesh Anandhan

DESCRIPTION
-----------------------------------------------------------------------------
Copyright (c) 2011, GEEKWAVE SOLUTIONS INC.

All rights reserved.
 ******************************************************************************/
package com.smartc.trading;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.smartc.connection.HttpConnection;
import com.smartc.connection.ParsedLoginData;
import com.smartc.ui.*;

public class TradeHome extends Activity implements OnItemClickListener {

	protected static final String TAG = "TradeHome";
	private static final int MENU_ADD_PRODUCT = 0;
	private final int PROGRESS_DLG = 0x01;
	private final int TIMEUPDATE = 1;
	private final int DELAY = 60000;
	// public static ArrayList<String> mItemName = new ArrayList<String>();
	// public static ArrayList<String> mItemPrize = new ArrayList<String>();
	// public static ArrayList<String> mItemTime = new ArrayList<String>();
	private ArrayList<Object> itemList;
	private ItemBean bean;

	ListView mItemListView;
	ListViewAdapter adapter;

	private TextView mItemCount;

	private HttpConnection mCityConnection;
	private ResponseHandler mResponse = new ResponseHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.trade_home);
		mItemCount = (TextView) findViewById(R.id.itemCount);
		// mItemListView = (ListView) findViewById(R.id.trade_items);
		// adapter = new ListViewAdapter(this.getApplicationContext(),
		// itemList);
		// mItemListView.setAdapter(adapter);
		// mItemListView.setOnItemClickListener(this);
	}

	@Override
	protected void onStart() {
		super.onStart();
		String domain = getResources().getString(R.string.domain);
		String query = getResources().getString(R.string.url_trade_home);
		String url = domain + query;
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onStart url:" + url);
		// ParsedLoginData.mIdUser = "1";//TO_DO
		mCityConnection = new HttpConnection();
		mCityConnection.setUrl(url);
		mCityConnection.clearParam();
		mCityConnection.AddParam("idUser", ParsedLoginData.mIdUser);
		mCityConnection.AddHandler(mResponse);
		mCityConnection.Execute();
	}

	public static class ViewHolder {
		ImageView ItemImage;
		TextView ItemName;
		TextView ItemPrize;
		TextView ItemsTime;
	}

	private class ListViewAdapter extends BaseAdapter {

		private LayoutInflater inflater;
		//private Context mContext;
		ArrayList<Object> mItemList;

		ListViewAdapter(Context context, ArrayList<Object> itemList) {
			super();
			//mContext = context;
			mItemList = itemList;
			this.inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return mItemList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.trade_items, null);

				holder.ItemImage = (ImageView) convertView
						.findViewById(R.id.item_image);
				holder.ItemName = (TextView) convertView
						.findViewById(R.id.itemTitle);
				holder.ItemPrize = (TextView) convertView
						.findViewById(R.id.itemPrize);
				holder.ItemsTime = (TextView) convertView
						.findViewById(R.id.itemTime);

				convertView.setTag(holder);
			} else
				holder = (ViewHolder) convertView.getTag();

			ItemBean bean = (ItemBean) itemList.get(position);

			holder.ItemImage.setImageResource(bean.getImage());
			holder.ItemName.setText(bean.getItemName());
			holder.ItemsTime.setText(bean.getItemTime());
			holder.ItemPrize.setText(bean.getItemPrize());

			return convertView;
		}
	}

	public class ItemBean {
		String mItemName;
		String mItemPrize;
		String mItemTime;
		int image;

		public String getItemName() {
			return mItemName;
		}

		public void setItemName(String name) {
			this.mItemName = name;
		}

		public String getItemPrize() {
			return mItemPrize;
		}

		public void setItemPrize(String itemprize) {
			this.mItemPrize = itemprize;
		}

		public String getItemTime() {
			return mItemTime;
		}

		public void setItemTime(String itemtime) {
			this.mItemTime = itemtime;
		}

		public int getImage() {
			return image;
		}

		public void setImage(int image) {
			this.image = image;
		}

	}

	public void AddObjectToList(int image, String name, String prize,
			String time) {

		bean = new ItemBean();
		bean.setItemName(name);
		bean.setItemPrize(prize);
		bean.setItemTime(time);
		bean.setImage(image);
		itemList.add(bean);
	}

	public class ResponseHandler extends DefaultHandler {

		//private boolean TradeProducts = false;
		//private boolean Products = false;
		//private boolean mStatus = false;
		private boolean nmTradeProduct = false;
		private boolean nrTradeProductPrice = false;
		private boolean nrMaxHour = false;
		private boolean dtTradeStart = false;
		private boolean idTradeProduct = false;
		private boolean nrTradeHighPrice =false;

		public ArrayList<String> mItemName = new ArrayList<String>();
		public ArrayList<String> mItemTime = new ArrayList<String>();
		public ArrayList<String> mItemPrize = new ArrayList<String>();
		public ArrayList<String> mBidStartTime = new ArrayList<String>();
		public ArrayList<String> mIdTradeProduct = new ArrayList<String>();
		public ArrayList<String> mItemBidPrize = new ArrayList<String>();
		@Override
		public void characters(char[] ch, int start, int length)
				throws SAXException {
			if (this.nmTradeProduct) {
				mItemName.add(new String(ch, start, length));
			} else if (this.nrTradeProductPrice) {
				mItemPrize.add(new String(ch, start, length));
			} else if (this.nrMaxHour) {
				mItemTime.add(new String(ch, start, length));
			} else if (this.dtTradeStart) {
				mBidStartTime.add(new String(ch, start, length));
			} else if (this.idTradeProduct) {
				mIdTradeProduct.add(new String(ch, start, length));
			} else if (this.nrTradeHighPrice) {
				mItemBidPrize.add(new String(ch, start, length));
			}
		}

		@Override
		public void endElement(String uri, String localName, String qName)
				throws SAXException {
			if (localName.equals("TradeProducts")) {
				//this.TradeProducts = false;
				Message myMessage = new Message();
				myMessage.obj = "PRODUCT";
				handler.sendMessage(myMessage);
			} else if (localName.equals("Products")) {
				//this.Products = false;
			} else if (localName.equals("nmTradeProduct")) {
				this.nmTradeProduct = false;
			} else if (localName.equals("nrTradeProductPrice")) {
				this.nrTradeProductPrice = false;
			} else if (localName.equals("nrMaxHour")) {
				this.nrMaxHour = false;
			} else if (localName.equals("dtTradeStart")) {
				this.dtTradeStart = false;
			} else if (localName.equals("idTradeProduct")) {
				this.idTradeProduct = false;
			} else if(localName.equals("nrTradeHighPrice")){
				this.nrTradeHighPrice = false;
			}
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (localName.equals("TradeProducts")) {
				//this.TradeProducts = true;
				mItemName.clear();
				mItemTime.clear();
				mItemPrize.clear();
				mBidStartTime.clear();
				mIdTradeProduct.clear();
				mItemBidPrize.clear();
			} else if (localName.equals("Products")) {
				//this.Products = true;
			} else if (localName.equals("nmTradeProduct")) {
				this.nmTradeProduct = true;
			} else if (localName.equals("nrTradeProductPrice")) {
				this.nrTradeProductPrice = true;
			} else if (localName.equals("nrMaxHour")) {
				this.nrMaxHour = true;
			} else if (localName.equals("dtTradeStart")) {
				this.dtTradeStart = true;
			} else if (localName.equals("idTradeProduct")) {
				this.idTradeProduct = true;
			} else if(localName.equals("nrTradeHighPrice")){
				this.nrTradeHighPrice = true;
			}
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage msg:" + (String) msg.obj);
			String loginmsg = (String) msg.obj;
			if (loginmsg != null && loginmsg.equals("PRODUCT")) {
				removeDialog(PROGRESS_DLG);

				int count = mResponse.mItemName.size();
				String item = getResources().getString(R.string.items_count);
				if (count == 1)
					item.subSequence(0, 3);

				mItemCount.setText(count + " " + item);

				itemList = new ArrayList<Object>();
				for (int i = 0; i < mResponse.mItemName.size(); i++) {
					String prize = mResponse.mItemBidPrize.get(i);
					String time = mResponse.mItemTime.get(i);
					String date = mResponse.mBidStartTime.get(i);
					String ellapsed_time = CalculateElapsedTime(date, time);
					AddObjectToList(R.drawable.app_icon, mResponse.mItemName
							.get(i), "Rs." + prize, ellapsed_time);
				}

				mItemListView = (ListView) findViewById(R.id.trade_items);
				adapter = new ListViewAdapter(TradeHome.this
						.getApplicationContext(), itemList);
				mItemListView.setAdapter(adapter);
				mItemListView.setOnItemClickListener(TradeHome.this);
				handler.sendEmptyMessageDelayed(TIMEUPDATE, DELAY);
			}
			if (msg.what == TIMEUPDATE) {
				String domain = getResources().getString(R.string.domain);
				String query = getResources()
						.getString(R.string.url_trade_home);
				String url = domain + query;
				Log.i(TAG, "handleMessage url:" + url);
				//ParsedLoginData.mIdUser = "1";// TO_DO
				mCityConnection = new HttpConnection();
				mCityConnection.setUrl(url);
				mCityConnection.clearParam();
				mCityConnection.AddParam("idUser", ParsedLoginData.mIdUser);
				mCityConnection.AddHandler(mResponse);
				mCityConnection.Execute();
			}
		}
	};

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long id) {
		if (AccountLogin.DEBUG)
			Log.i(TAG, "onItemClick position" + position);
		// ItemBean bean = (ItemBean) adapter.getItem(position);
		Intent intent = new Intent();
		intent.setClass(TradeHome.this, ProdDescription.class);
		intent.putExtra("idTradeProduct", mResponse.mIdTradeProduct
				.get(position));
		startActivity(intent);
	}

	private String CalculateElapsedTime(String Date, String Time) {
		String ItemTime = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = (Date) format.parse(Date);
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage date:" + date.toString());
			long time = date.getTime();
			Calendar cal = Calendar.getInstance();
			cal.setTimeInMillis(time);
			cal.add(Calendar.HOUR,/* 116 */Integer.parseInt(Time));

			Date end = cal.getTime();
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage date:" + end.toString());
			Calendar cal1 = Calendar.getInstance();

			Date now = cal1.getTime();
			if (AccountLogin.DEBUG)
				Log.i(TAG, "handleMessage now date:" + now.toString());
			long l1 = end.getTime();
			long l2 = now.getTime();
			if (end.after(now)) {
				long diff = l1 - l2;

				long secondInMillis = 1000;
				long minuteInMillis = secondInMillis * 60;
				long hourInMillis = minuteInMillis * 60;
				long dayInMillis = hourInMillis * 24;
				long yearInMillis = dayInMillis * 365;

				long elapsedYears = diff / yearInMillis;
				diff = diff % yearInMillis;
				long elapsedDays = diff / dayInMillis;
				diff = diff % dayInMillis;
				long elapsedHours = diff / hourInMillis;
				diff = diff % hourInMillis;
				long elapsedMinutes = diff / minuteInMillis;
				diff = diff % minuteInMillis;
				long elapsedSeconds = diff / secondInMillis;

				// elapsedHours += elapsedDays*24;
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedYears:" + elapsedYears);
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedDays:" + elapsedDays);
				if (AccountLogin.DEBUG)
					Log.i(TAG, "handleMessage elapsedHours:" + elapsedHours);
				if (AccountLogin.DEBUG)
					Log
							.i(TAG, "handleMessage elapsedMinutes:"
									+ elapsedMinutes);
				if (AccountLogin.DEBUG)
					Log
							.i(TAG, "handleMessage elapsedSeconds:"
									+ elapsedSeconds);
				ItemTime = elapsedDays + "Day " + elapsedHours + "hr "
						+ elapsedMinutes + "Mins";
			} else {
				ItemTime = "0";
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return ItemTime;
	}

	@Override
	protected void onStop() {
		super.onStop();
		handler.removeMessages(TIMEUPDATE);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// Added the icons to the context menu
		menu.add(0, MENU_ADD_PRODUCT, 0, getResources().getString(
				R.string.add_product));

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_ADD_PRODUCT:
			Intent intent = new Intent();
			intent.setClass(TradeHome.this, SellProduct.class);
			startActivity(intent);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

}
